#include<iostream>
#include<vector>
using namespace std;

struct TreeNode {
    int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode() : val(0), left(nullptr), right(nullptr) {}
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
	TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int maxSum = INT_MIN;
public:

    int _maxPathSum(TreeNode* root)
    {
        if (root == nullptr)
            return 0;

        int leftMaxVal = max(_maxPathSum(root->left), 0);
        int rightMaxVal = max(_maxPathSum(root->right), 0);

        int tmpSum = root->val + leftMaxVal + rightMaxVal;
        maxSum = max(maxSum, tmpSum);
        return max(leftMaxVal, rightMaxVal) + root->val;
    }

    int maxPathSum(TreeNode* root) {
        _maxPathSum(root);
        return maxSum;
    }
};